'use strict'

var qiniu = {
  upload:"https://up.qbox.me",
  bucket:"https://oimcnea2a.qnssl.com/",
  noBucket:'oimcnea2a.qnssl.com/',
  bucketName:'rijinop-upload-image'
}

var newId = $('mata[name=newId]').attr('content')
var id = $('input[name=id]').val()
var qrId = (id && id!=='' && id!==0)?id:newId

var domain = 'http://audio.enjoyshadow.com/qrcode/'+qrId
var qrcodeBin = 'http://qr.topscan.com/api.php?text='

console.log(qrcodeBin+domain)


function base64Encode(input){
  var rv;
  rv = encodeURIComponent(input);
  rv = unescape(rv);
  rv = window.btoa(rv);
  return rv.replace('/','_').replace('+','-');
}

function loadPoster(imageUrl){
  var qrUrl = imageUrl+'?watermark/1/image/'+baseQr+'/gravity/South/dy/220/ws/0.4'
  var $posterQr = '<div class="saveas"><a href="'+qrUrl+'" target="_blank">点击后另存为<br>二维码海报</a></div>'
  $('#posterQr').html($posterQr)
  console.log(qrUrl)
}

function removePoster(){
  $('#posterQr').empty()
}


var baseQr = base64Encode(qrcodeBin+domain)



function uploadToQiniu(file,token,key,cb){
    var xhr = new XMLHttpRequest();
    xhr.open('POST', qiniu.upload, true);
    var formData, startDate;
    formData = new FormData();
    if (key !== null && key !== undefined) formData.append('key', key);
    formData.append('token', token);
    formData.append('file', file);
    var taking;
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var nowDate = new Date().getTime();
        taking = nowDate - startDate;
        var x = (evt.loaded) / 1024;
        var y = taking / 1000;
        var uploadSpeed = (x / y);
        var formatSpeed;
        if (uploadSpeed > 1024) {
          formatSpeed = (uploadSpeed / 1024).toFixed(2) + "Mb\/s";
        } else {
          formatSpeed = uploadSpeed.toFixed(2) + "Kb\/s";
        }
        let percentComplete = Math.round(evt.loaded * 100 / evt.total);
        console && console.log(percentComplete, ",", formatSpeed);
      }
    }, false);
    xhr.onreadystatechange = handler;

    function handler(response){

      if (this.readyState !== 4) {
        return;
      }
      if (xhr.status === 200) {
        var blkRet = JSON.parse(xhr.responseText);
        cb(blkRet)
      } else {
        throw(new Error(xhr.statusText));
      }
    }
    startDate = new Date().getTime();
    xhr.send(formData);
}






$(function(){
   var $ = jQuery,
    $face = $('#faceList'),
   $faceUrl = $('#faceUrl'),
    $qun = $('#qunList'),
    $qunUrl = $('#qunUrl'),
     $poster = $('#posterList'),
    $posterUrl = $('#posterUrl'),
    ratio =  1,
    thumbnailWidth = 100 * ratio,
    thumbnailHeight = 100 * ratio,
    faceLoader,qunLoader,posterLoader;
  var $btn = $('<div class="filePanel"><span></span></div>');

  faceLoader = WebUploader.create({
    pick: {
      id: '#facePicker'
    },
    swf: '../utils/Uploader.swf',
    chunked: false,
    chunkSize: 512 * 1024,
    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
    disableGlobalDnd: true,
    fileNumLimit: 1,
    fileSizeLimit: 200 * 1024 * 1024,    // 200 M
    fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
  });

  qunLoader = WebUploader.create({
    pick: {
      id: '#qunPicker'
    },
    swf: '../utils/Uploader.swf',
    chunked: false,
    chunkSize: 512 * 1024,
    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
    disableGlobalDnd: true,
    fileNumLimit: 1,
    fileSizeLimit: 200 * 1024 * 1024,    // 200 M
    fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
  });

  posterLoader = WebUploader.create({
    pick: {
      id: '#posterPicker'
    },
    swf: '../utils/Uploader.swf',
    chunked: false,
    chunkSize: 512 * 1024,
    // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
    disableGlobalDnd: true,
    fileNumLimit: 1,
    fileSizeLimit: 200 * 1024 * 1024,    // 200 M
    fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
  });



  faceLoader.on('filesQueued', function(file) {
    uploadQiniuFile(file,$face,$faceUrl,this)
  });

  qunLoader.on('filesQueued', function(file) {
    uploadQiniuFile(file,$qun,$qunUrl,this)
  });

  posterLoader.on('filesQueued', function(file) {
    uploadQiniuFile(file,$poster,$posterUrl,this)
  });


  function uploadQiniuFile(file,thumb,value,handle){
    var uploadFile = file[0].source.source
    console.log(uploadFile)
    var fileSeg = file[0].name.split('.')
    var key = 'audio_face_' +(new Date()).valueOf() + '.' + fileSeg[1];
    console.log(key)
    $.ajax('https://biz-op.rijin.com/api/port/getQiniuToken',{
      method: 'POST',
      type: 'json',
      data: {
        key: key
      },
      success: function(d){
        if(d && d.success){
          console.log('token:',d.token)
          var token = d.token
          uploadToQiniu(uploadFile,token,key,function(bkt){
            previewFile(bkt.key,file[0],thumb,value,handle)
          })
        }else{
          console.log('上传发生错误')
        }
      }
    })
  }

  var readFaceUrl  = $('#faceUrl').val();
  if(readFaceUrl && readFaceUrl!=='##invalid##'){
    var $readFaceBtn = $('<div id="faceFile" class="filePanel"><span></span></div>')
    var $readFaceImg = $('<img src="'+readFaceUrl+'" width="'+thumbnailWidth+'" height="'+thumbnailHeight+'">')
    $face.append($readFaceBtn).append($readFaceImg)

    $readFaceBtn.on('click',function(){
      $face.empty()
      $('#faceUrl').val('##invalid##')
    })
  }

  var readQunUrl  = $('#qunUrl').val();
  if(readQunUrl && readQunUrl!=='##invalid##'){
    var $readQunBtn = $('<div id="qunFile" class="filePanel"><span></span></div>')
    var $readQunImg = $('<img src="'+readQunUrl+'" width="'+thumbnailWidth+'" height="'+thumbnailHeight+'">')
    $qun.append($readQunBtn).append($readQunImg)

    $readQunBtn.on('click',function(){
      $qun.empty()
      $('#qunUrl').val('##invalid##')
    })
  }


  var readPosterUrl  = $('#posterUrl').val();
  if(readPosterUrl && readPosterUrl!=='##invalid##'){
    var $readPosterBtn = $('<div class="filePanel"><span></span></div>')
    var $readPosterImg = $('<img src="'+readPosterUrl+'" width="'+thumbnailWidth+'" height="'+thumbnailHeight+'">')
    $poster.append($readPosterBtn).append($readPosterImg)

    loadPoster(readPosterUrl)

    $readPosterBtn.on('click',function(){
      $poster.empty()
      removePoster()
      $('#posterUrl').val('##invalid##')
    })
  }





  function previewFile(key,file,thumb,value,handle){

    var $btn = $('<div class="filePanel"><span></span></div>')
    handle.makeThumb(file,function(err,src){
      if(err){
        console.log(err)
      }
      var $img = $('<img src="'+src+'">')
      thumb.append($img).append($btn)
    //  进行拼接生成缩略图
    },thumbnailWidth,thumbnailHeight)

    var imageUrl = qiniu.bucket+key
    value.val(imageUrl)


    if(thumb === $poster){
      loadPoster(imageUrl)
    }


    $btn.on('click',function(){
      handle.removeFile(file)
      thumb.empty()
      if(thumb === $poster){
        removePoster()
      }
      value.val('##invalid##')
    })
  }




  $('.submit').on('click', function() {

    if($('#faceUrl').val() === '##invalid##'){
      alert('没有设置封面！')
      return false
    }
    if($('#qunUrl').val() === '##invalid##'){
      alert('没有设置微信群！')
      return false
    }

    if(!$('input[name="qun"]').val()){
      alert('没有设置群名称！')
      return false
    }
    if(!$('input[name="url"]').val()){
      alert('没有设置语音地址！')
      return false
    }
    if(!$('input[name="title"]').val()){
      alert('没有设置标题！')
      return false
    }
    if(!$('textarea[name="desc"]').val()){
      alert('没有设置分享描述！')
      return false
    }


  })
  $('.test').click(function(){
    console.log(!$('input[name="qun"]').val())
  })

  console.log()

})

